package org.dreamwork.jasmine2.engine;

import org.dreamwork.jasmine2.web.controls.Page;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-2-3
 * Time: 10:15:59
 */
public class HttpContext {
    private Page page;
    private ServletContext application;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;

    private Map<String, Object> attrs = new HashMap<String, Object> ();

    public static final int SCOPE_PAGE = 0, SCOPE_REQUEST = 1,
            SCOPE_SESSION = 2, SCOPE_APPLICATION = 3;

    private static ThreadLocal<HttpContext> threadLocal = new ThreadLocal<HttpContext> ();

    public static HttpContext current () {
        return threadLocal.get ();
    }

    HttpContext () {
        threadLocal.set (this);
    }

    public Page getPage () {
        return page;
    }

    public void setPage (Page page) {
        this.page = page;
    }

    public ServletContext getApplication () {
        return application;
    }

    void setApplication (ServletContext application) {
        this.application = application;
    }

    public HttpServletRequest getRequest () {
        return request;
    }

    void setRequest (HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse () {
        return response;
    }

    void setResponse (HttpServletResponse response) {
        this.response = response;
    }

    public HttpSession getSession () {
        return session;
    }

    void setSession (HttpSession session) {
        this.session = session;
    }

    public void setAttribute (String key, Object value) {
        attrs.put (key, value);
    }

    public Object getAttribute (String key) {
        return attrs.get (key);
    }

    public Object getAttribute (String key, int scope) {
        switch (scope) {
            case SCOPE_PAGE : return getAttribute (key);
            case SCOPE_REQUEST : return request.getAttribute (key);
            case SCOPE_SESSION : return session.getAttribute (key);
            case SCOPE_APPLICATION : return application.getAttribute (key);
        }
        throw new IllegalArgumentException ("Invalid argument scope !");
    }

    public Object findAttribute (String key) {
        for (int i = 0; i <= 3; i ++ ) {
            try {
                Object obj = getAttribute (key, i);
                if (obj != null) return obj;
            } catch (IllegalArgumentException ignore) {

            }
        }
        return null;
    }
}